﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Radiation___IM.Data;

namespace Radiation___IM.Users
{
    public class PermissionGroupManager
    {
        private static PermissionGroupManager _instance;

        public static void Init()
        {
            _instance = new PermissionGroupManager();
        }

        public static PermissionGroupManager Instance
        {
            get
            {
                return _instance;
            }
        }

        // Dynamic part

        private Dictionary<string,PermissionGroup> m_groups;

        public PermissionGroup this[string group]
        {
            get
            {
                if (m_groups.ContainsKey(group))
                    return m_groups[group];
                return null;
            }
        }

        public PermissionGroupManager()
        {
            m_groups = new Dictionary<string, PermissionGroup>();
        }

        public bool groupExists(string name)
        {
            return m_groups.ContainsKey(name);
        }

        public File getFile()
        {
            File final = new File("perm_groups.dat");

            foreach (PermissionGroup group in m_groups.Values)
                final.addLine(group.Name, group.serialize());

            return final;
        }

        public void setFile(File to_set)
        {
            this.m_groups.Clear();

            foreach (string key in to_set.Values)
            {
                PermissionGroup group = new PermissionGroup(key);
                group.unserialize(to_set[key]);
                this.addGroup(group);
            }
        }


        public rvalue addGroup(PermissionGroup group)
        {
            if (!groupExists(group.Name))
            {
                lock (m_groups)
                {
                    m_groups.Add(group.Name, group);
                }

                return rvalue.PERMISSION_GROUP_ADDED;
            }
            else
                return rvalue.PERMISSION_GROUP_ALREADY_EXISTS;
        }

        public rvalue removeGroup(string group_name)
        {
            if (groupExists(group_name))
            {
                lock (m_groups)
                {
                    m_groups.Remove(group_name);
                }

                return rvalue.PERMISSION_GROUP_DELETED;
            }
            else
                return rvalue.PERMISSION_GROUP_NOT_FOUND;
        }
    }
}
